<template>
  <!-- 门诊医生-处方-table -->

  <div>
    <BaseTable
      class="table-style mt-2"
      bordered
      max-fill
      column-code="00001134"
      :pagination="false"
      :extra-height="64"
      :scroll="{ x: 2000, y: 500 }"
      :row-class-name="getRowClass"
      :expanded-row-keys="tableInfo.expandedRowKeys"
      :data-source="tableData"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'link'">
          <div class="table-link"></div>
        </template>
        <template v-if="column.dataIndex === 'yzzt'">
          <a-tag v-if="record.yzzt === 0" color="blue">新开立</a-tag>
          <a-tag v-if="record.yzzt === 1" color="green">已签署</a-tag>
          <a-tag v-if="record.yzzt === 2" color="red">已作废</a-tag>
        </template>
        <template v-if="column.dataIndex === 'sfxm'">
          <EditCell title="药品名称">
            <SelectMedicine
              v-model:value="record.sfxm"
              :row-data="record"
              :insure-status="record?.insureStatus"
              :auto-focus="record.isNew && focusCell === record.key + '药品名称'"
              :search-params="{ jsyplb: tableInfo.medicineType, drugStoreId: tableInfo.drugStoreId }"
              @select="onSelectMedicine($event, record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'yf'">
          <EditCell title="给药途径" :disabled="record.isChild">
            <SelectTable
              v-model:value="record.yf.fyff"
              :auto-focus="record.isNew && focusCell === record.key + '用法'"
              :table-width="360"
              type="用法"
              @select="onSelectWays($event, record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'pl' && record.pl">
          <EditCell title="频次" :disabled="record.isChild">
            <SelectTable
              v-model:value="record.pl.pl"
              :auto-focus="record.isNew && focusCell === record.key + '频率'"
              :table-width="360"
              type="频率"
              @select="onSelectFrequency($event, record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'jlsl'">
          <EditCell title="剂量">
            <BaseInput
              v-model:value="record.jlsl"
              v-input:int
              v-input-selection
              :auto-focus="record.isNew && focusCell === record.key + '剂量'"
              placeholder="请输入"
              :suffix="record?.jldw"
              @keydown.enter="focusCell = record.key + (record.isChild ? '数量' : '天数')"
              @blur="onCalc(record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'cfts'">
          <EditCell title="天数" :disabled="record.isChild">
            <BaseInput
              v-model:value="record.cfts"
              v-input:int
              v-input-selection
              :auto-focus="record.isNew && focusCell === record.key + '天数'"
              suffix="天"
              placeholder="请输入"
              @keydown.enter="focusCell = record.key + '数量'"
              @blur="onDaysBlur(record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'sl'">
          <EditCell title="总量">
            <BaseInput
              v-model:value="record.sl"
              v-input:int
              v-input-selection
              :auto-focus="record.isNew && focusCell === record.key + '数量'"
              :suffix="record.sfxm?.dw"
              placeholder="请输入"
              @keydown.enter="saveAndAdd(record)"
              @blur="editRow(record) && onCalcTotal"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'orderType'">
          {{ record.orderType === 2 ? '套餐' : '单项' }}
        </template>
        <!-- <template v-if="column.dataIndex === 'status'"> -->
        <!-- <a-tag v-if="record.tjzt === 0" color="blue">未签署</a-tag> -->
        <!-- <a-tag v-if="record.yzzt === 2" color="red">已作废</a-tag>
        <a-tag v-else-if="record.zxzt === 1" color="green">已执行</a-tag>
        <a-tag v-else-if="record.jfzt === 1" color="green">已收费</a-tag>
        <a-tag v-else-if="record.jfzt === 0" color="blue">未收费</a-tag> -->
        <!-- </template> -->
        <template v-if="column.dataIndex === 'jfzt'">
          <a-tag v-if="record.jfzt === 0" color="blue">未收费</a-tag>
          <a-tag v-if="record.jfzt === 1" color="green">已收费</a-tag>
          <a-tag v-if="record.jfzt === 2" color="red">已作废</a-tag>
        </template>
        <template v-if="column.dataIndex === 'zxzt'">
          <a-tag v-if="record.zxzt === 0" color="blue">未执行</a-tag>
          <a-tag v-if="record.zxzt === 1" color="green">已执行</a-tag>
        </template>
        <template v-if="column.dataIndex === 'yssm'">
          <EditCell title="医生说明">
            <a-input v-model:value="record.yssm" placeholder="请输入" @blur="editRow(record)" />
          </EditCell>
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button v-if="!record.isChild && record.orderType !== 2" :disabled="record.zxzt === 1" type="link" size="small" @click="addChildRow(record)">
            子医嘱
          </a-button>
          <BaseButton
            v-if="record.yzzt === 1 && record.jfzt === 0 && record.zxzt === 0"
            danger
            type="text"
            size="small"
            confirm-text="撤销签署?"
            @click="onDeleteSign(record)"
          >
            撤签
          </BaseButton>
          <BaseButton v-if="record.isChild && record.yzzt !== 1" danger type="text" size="small" confirm-text="作废子医嘱?" @click="onDeleteChild(record)">
            作废子医嘱
          </BaseButton>
          <BaseButton v-if="!record.isChild && record.zxzt !== 1" danger size="small" type="text" confirm-text="确认作废？" @click="onDelete(record)">
            作废
          </BaseButton>

          <a-button v-if="record?.insureStatus === 1" size="small" danger type="link" @click="onClickFunded(record, 2)">强制自费</a-button>
          <BaseButton v-if="record?.insureStatus === 2" confirm-text="撤销自费？" danger size="small" type="text" @click="onClickFunded(record, 1)"
            >撤销自费</BaseButton
          >
          <!-- <a-button type="link" size="small" @click="onClickResults(record)"> 皮试结果 </a-button> -->
        </template>
      </template>
      <template #footer>
        <div class="sticky bottom-0 flex justify-between pl-20 items-center">
          <div class="text-center flex-1">
            <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :icon="h(SaveOutlined)" :disabled="!isHaveNewRow()" @click="saveNewRows()"> 保存 </a-button>
          </div>
          <div class="text-right w-20 pr-6 font-semibold text-base">￥{{ totalPrice }}</div>
        </div>
      </template>
    </BaseTable>
    <!-- <SkinTestResults v-model:open="open" :row-data="rowData" /> -->
  </div>
</template>
<script setup>
import { ref, h, watch } from 'vue'
import { PlusOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import cofirmModal from '@/utils/confirm'
import { getIds } from '@/utils/tools'
// import SkinTestResults from '@/components/SkinTestResults'
import useDoctorStore from '../store'
import useStore from './store'

// const open = ref(false)
const doctorStore = useDoctorStore()
const thisStore = useStore()
const focusCell = ref('')
// const rowData = ref({})
const medicationData = ref([])
const props = defineProps({
  tableKey: {
    type: String,
    default: ''
  }
})

const tableData = ref({})
const tableInfo = ref({})
const totalPrice = ref('0.00')
const getTotal = async () => {
  const { data, code } = await post('/outp/outpClinicalOrder/getOutpClinicalOrderAmount', {
    jzbh: thisStore.jzbh, //就诊编号
    yzlb: ['2', '4'],
    iscz: '',
    cfbh: tableInfo.value.cfbh
  })
  if (code !== 0) return
  totalPrice.value = data?.amount || '0.00'
}
watch(
  () => thisStore.tableList,
  (val) => {
    const table = val.find((item) => item.tableKey === props.tableKey)
    if (table?.tableKey) {
      const { dataSource = [] } = table
      tableData.value = dataSource
      tableInfo.value = table
      getTotal()
    }
  },
  {
    immediate: true
  }
)

const isHaveNewRow = () => {
  const res = tableData.value.some((item) => item.isNew)
  thisStore.isHaveNewRow = res
  return res
}
// 撤销签署
const onDeleteSign = async (row) => {
  const { code, msg } = await post('/outp/mzys/signedDoctor', {
    yzid: [row.id],
    yzzt: 0
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  await thisStore.getData()
}
//删除空行
const onDeleteEmptyRow = () => {
  tableData.value = tableData.value.filter((item) => item.sfxm?.mc)
  tableData.value.map((item) => {
    item.children = item.children?.filter((child) => child.sfxm?.mc)
  })
}
//保存并新增行
const saveNewRows = async () => {
  onDeleteEmptyRow()
  fetchSave()
}

const editRow = (row) => !row.isNew && fetchSave()

//保存医嘱
const fetchSave = async () => {
  const newData = tableData.value.map((row) => {
    return {
      cfbh: row.tableKey, //处方编号
      jzbh: doctorStore.currentPatient.jzbh, //编号
      drugStoreId: tableInfo.value.drugStoreId || '', //药房id
      drugStoreName: tableInfo.value.drugStoreName || '', //药房name
      ...row
    }
  })
  const { code, msg } = await post('/outp/mzys/doSaveOutpClinicalOrderInfoList', newData)
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('保存成功')
  await thisStore.getData()
}
const saveAndAdd = async (row) => {
  if (row.isChild) {
    const fRow = tableData.value.find((item) => item.key === row.fkey)
    await fetchSave(fRow)
    const storeRow = tableData.value.find((item) => item.key === fRow.key)
    addChildRow(storeRow)
  } else {
    const flag = await fetchSave(row)
    !flag && addRow()
  }
}

//选药
const onSelectMedicine = (medicine, row) => {
  row.sfxm = medicine
  // row.jlsl = 1
  // row.cfts = row.cfts || 1
  row.sl = 1
  row.jldw = medicine?.jldw
  focusCell.value = `${row.key}${row.isChild ? '剂量' : '用法'}`
  onCalc(row)
  getSelectUsage(medicine, row)
}

// 获取用法和频次
const getSelectUsage = async (medicine, row) => {
  const { code, data, msg } = await post('/common/masterData/getDictDrugDefaultUsage', { bh: medicine.bh })
  if (code !== 0) return message.error(msg)
  medicationData.value = data
  data[0]?.fyff && (data[0].fyff.isSelectDrug = true)
  data[0]?.pl && (data[0].pl.isSelectDrug = true)
  data[0]?.fyff && onSelectWays(data[0].fyff, row)
  data[0]?.pl && onSelectFrequency(data[0].pl, row)
  data[0]?.day && (row.cfts = data[0].day)
  data[0]?.dose && (row.jlsl = data[0].dose)
}

//选用法
const onSelectWays = (selected, row) => {
  if (medicationData.value.length > 0) {
    const isNull = medicationData.value.some((i) => i.fyff)
    const selectUsage = medicationData.value.some((i) => i.fyff?.fyffid === selected?.fyffid)
    isNull && !selectUsage && message.error('该给药途径不在设置范围内，请注意')
  }
  row.yf = selected
  row?.children.length && row.children.forEach((item) => (item.yf = selected))
  !selected.isSelectDrug && (focusCell.value = row.key + '频率')
  editRow(row)
}
//选频率
const onSelectFrequency = (selected, row) => {
  if (medicationData.value.length > 0) {
    const isNull = medicationData.value.some((i) => i.pl)
    const selectUsage = medicationData.value.some((i) => i.pl?.plid === selected?.plid)
    isNull && !selectUsage && message.error('该给药频次不在设置范围内，请注意')
  }
  row.pl = selected
  row?.children.length && row.children.forEach((item) => (item.pl = selected))
  !selected.isSelectDrug && (focusCell.value = row.key + '剂量')
  // row.yssm = `${row?.yssm || ''}  ${selected?.pltime || ''}`
  onCalc(row)
}

const onDelete = async (row) => {
  if (row.isNew) {
    if (row.isSuit) {
      tableData.value = tableData.value.filter((item) => item.tcid !== row.tcid)
    } else {
      const index = tableData.value.findIndex((item) => item.key === row.key)
      tableData.value.splice(index, 1)
    }
    thisStore.tableList.find((item) => item.tableKey === props.tableKey).dataSource = tableData.value
    message.success('删除成功')
  } else {
    fetchDelete(row)
  }
}
const onDeleteChild = async (row) => {
  if (row.isNew) {
    const fData = tableData.value.find((item) => item.key === row.fkey)
    const index = fData.children.findIndex((item) => item.key === row.key)
    fData.children.splice(index, 1)
  } else {
    fetchDelete(row)
  }
}
const fetchDelete = async (row) => {
  const { code, msg } = await post('/outp/mzys/doDelOutpClinicalOrderInfo', {
    yzbh: row.id
  })
  if (code !== 0) return message.error(msg || '作废失败')
  message.success('作废成功')
  thisStore.getData()
}

// 自费
const onClickFunded = async (row, state) => {
  const { code, msg } = await post('/outp/mzys/doCompulsorySelfpaymentInfo', {
    insureStatus: state,
    yzbh: row.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  thisStore.getData()
}

// 皮试结果
// const onClickResults = (row = {}) => {
//   rowData.value = row
//   open.value = true
// }

//添加行
const addRow = async () => {
  onDeleteEmptyRow()
  if (getIds(tableData.value).length === 5) {
    const isConfirm = await cofirmModal({ title: '提示', content: '单张处方不建议超过5个药，是否继续添加？' })
    if (!isConfirm) return
  }
  const newRow = thisStore.generateRow()
  tableInfo.value.expandedRowKeys.push(newRow.key)
  tableData.value.push({ ...newRow, tableKey: tableInfo.value.tableKey, cfbh: tableInfo.value.cfbh })
  focusCell.value = newRow.key + '药品名称'
}
//添加子医嘱
const addChildRow = async (row) => {
  onDeleteEmptyRow()
  if (getIds(tableData.value).length === 5) {
    const isConfirm = await cofirmModal({ title: '提示', content: '单张处方不建议超过5个药，是否继续添加？' })
    if (!isConfirm) return
  }
  if (!row.sfxm || !row.yf || !row.pl || !row.sl || !row.cfts) return message.error('请先填写主医嘱')
  const extendParams = { yf: row.yf, pl: row.pl, cfts: row.cfts }
  const newRow = thisStore.generateRow(true)
  const addRow = { fkey: row.key, cfbh: row.cfbh, ...newRow, ...extendParams }
  row.isNew = true
  row.children.push(addRow)
  focusCell.value = addRow.key + '药品名称'
}
const onDaysBlur = (row) => {
  row.children.length && row.children.forEach((item) => (item.cfts = row.cfts))
  onCalc(row)
}
const onCalc = async (row) => {
  if (!row.cfts || !row.jlsl || !row.pl?.pl || !row.sfxm) return
  const { data, code } = await post('/outp/mzys/calculateTheTotal', {
    cfts: row.cfts,
    jlsl: row.jlsl,
    pl: row.pl,
    sfxm: row.sfxm
  })
  if (code !== 0) return message.error('计算失败')
  row.sl = data
  editRow(row)
}
const getRowClass = (record) => {
  const className = {
    'table-row-suit': record.isSuit,
    'table-row-new': record.isNew,
    'table-row-readonly-not-last': record.jfzt === 1,
    'table-row-disabled': record.yzzt === 2 || record.zxzt === 1
  }
  return Object.keys(className)
    .filter((key) => className[key])
    .join(' ')
}
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
